package com.xlh.openai.utils;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

/**
 * request工具类
 *
 * @author cheer
 */
public class RequestUtil {

    /**
     * 获取请求Ip地址
     */
    public static String getIpAddress(HttpServletRequest request) {
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (StringUtils.isNotBlank(xForwardedFor) && !"unKnown".equalsIgnoreCase(xForwardedFor)) {
            //多次反向代理后会有多个ip值，第一个ip才是真实ip
            int index = xForwardedFor.indexOf(',');
            if (index != -1) {
                return xForwardedFor.substring(0, index);
            } else {
                return xForwardedFor;
            }
        }

        String xRealIp = request.getHeader("X-Real-IP");
        if (StringUtils.isNotBlank(xRealIp) && !"unKnown".equalsIgnoreCase(xRealIp)) {
            return xRealIp;
        }

        if (StringUtils.isBlank(xRealIp) || "unknown".equalsIgnoreCase(xRealIp)) {
            xRealIp = request.getHeader("Proxy-Client-IP");
        }
        if (StringUtils.isBlank(xRealIp) || "unknown".equalsIgnoreCase(xRealIp)) {
            xRealIp = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(xRealIp) || "unknown".equalsIgnoreCase(xRealIp)) {
            xRealIp = request.getHeader("HTTP_CLIENT_IP");
        }
        if (StringUtils.isBlank(xRealIp) || "unknown".equalsIgnoreCase(xRealIp)) {
            xRealIp = request.getHeader("HTTP_X_FORWARDED_FOR");
        }
        if (StringUtils.isBlank(xRealIp) || "unknown".equalsIgnoreCase(xRealIp)) {
            xRealIp = request.getRemoteAddr();
        }
        return xRealIp;
    }

}
